package gwt.immunology.server.service;

import gwt.immunology.client.service.SyndromeService;
import gwt.immunology.server.converter.SyndromeDtoConverter;
import gwt.immunology.shared.GenericDto;
import gwt.immunology.shared.ResultSetDto;

import java.util.List;

import models.Syndrome;
import play.Logger;
import play.modules.gwt2.GWT2Service;
import play.modules.gwt2.GWT2ServicePath;

@GWT2ServicePath("/immunology/syndrome")
public class SyndromeServiceImpl extends GWT2Service implements SyndromeService {

    @Override
    public GenericDto registerNewSyndrome(GenericDto syndromeDto) {
	GenericDto result = null;
	if (syndromeDto != null && !syndromeDto.isEmpty()) {
	    Syndrome syndrome = SyndromeDtoConverter.convertGenericDtoToSyndrome(syndromeDto);
	    Logger.info("registering new syndrome");
	    syndrome = Syndrome.em().merge(syndrome);
	    result = SyndromeDtoConverter.convertSyndromeToGenericDto(syndrome);
	} else {
	    Logger.warn("can't register syndrome with null value");
	}
	return result;
    }

    @Override
    public void deleteSyndromeById(Long syndromeId) {
	if (syndromeId != null) {
	    Syndrome syndrome = Syndrome.em().find(Syndrome.class, syndromeId);
	    if (syndrome != null) {
		Logger.info("deleting syndrome by id = " + syndromeId);
		Syndrome.em().remove(syndrome);
	    } else {
		Logger.warn("can't delete syndrome with null value");
	    }
	} else {
	    Logger.warn("can't delete syndrome by id = " + syndromeId);
	}
    }

    @Override
    public GenericDto getSyndromeById(Long syndromeId) {
	GenericDto result = null;
	if (syndromeId != null) {
	    Logger.info("retrieving syndrome by id = " + syndromeId);
	    Syndrome syndrome = Syndrome.em().find(Syndrome.class, syndromeId);
	    result = SyndromeDtoConverter.convertSyndromeToGenericDto(syndrome);
	} else {
	    Logger.warn("can't retrieve syndrome by id = " + syndromeId);
	}
	return result;
    }

    @Override
    public GenericDto editSyndrome(GenericDto syndromeDto) {
	GenericDto result = null;
	if (syndromeDto != null && !syndromeDto.isEmpty()) {
	    Syndrome syndrome = SyndromeDtoConverter.convertGenericDtoToSyndrome(syndromeDto);
	    Logger.info("editing syndrome with id = " + syndrome.syndromeId);
	    syndrome = Syndrome.em().merge(syndrome);
	    result = SyndromeDtoConverter.convertSyndromeToGenericDto(syndrome);
	} else {
	    Logger.warn("can't edit syndrome with null value");
	}
	return result;
    }

    @Override
    public ResultSetDto getAllSyndromes() {
	ResultSetDto result = null;
	Logger.info("retrieving all syndromes");
	List<Syndrome> syndromes = Syndrome.all().fetch();
	result = SyndromeDtoConverter.convertSyndromesToResultSetDto(syndromes);
	return result;
    }

}
